package com.jrwd.recycletest.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ${templefck} on 2018/7/18.
 */
public class JsonHelper {
    public static String tojson(Object object) {
        return JSON.toJSONString(object);
    }

    public static <T> T convert(String json, Class<T> type) {
        return JSON.parseObject(json, type);
    }

    public static <T> T convert(String json, TypeReference<T> type) {
        return JSON.parseObject(json, type);
    }

    public static <T> List<T> convertList(String json, Class<T> type) {
        try {
            List<T> result = JSON.parseArray(json, type);
            if (result == null)
            {
                result = new ArrayList<T>();
            }
            return result;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T convert(String json, Class<T> beanClass, Type clazz) {
        Type objectType = type(beanClass, clazz);
        return JSON.parseObject(json, objectType);
    }

    public static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }
}
